import React, { useCallback } from 'react';
import { useDocumentTitle } from '@src/utils';
import {
  useKanbanSearchParams,
  useKanbansQueryKey,
  useProjectInUrl,
  useTasksQueryKey,
  useTasksSearchParams,
} from '@src/screens/kanban/util';
import { KanbanColumn } from '@src/screens/kanban/kanban-column';
import styled from '@emotion/styled';
import { useKanbans, useReorderKanban } from '@src/utils/kanban';
import { SearchPanel } from '@src/screens/kanban/search-panel';
import { ScreenContainer } from '@src/components/lib';
import { useReorderTask, useTasks } from '@src/utils/task';
import { Spin } from 'antd';
import { CreateKanban } from '@src/screens/kanban/create-kanban';
import { TaskModal } from '@src/screens/kanban/task-modal';
import { DragDropContext, DropResult } from 'react-beautiful-dnd';
import { Drag, Drop, DropChild } from '@src/components/drag-and-drop';
import { Profiler } from '@src/components/profiler';

/**
 *
 * @constructor
 */
export const KanbanScreen = () => {
  useDocumentTitle('看板列表');
  // 当前的project 对象
  const { data: currentProject } = useProjectInUrl();
  // 获取看板的所有数据
  const { data: kanbans, isLoading: kanbanIsLoading } = useKanbans(useKanbanSearchParams());
  // 获取所有任务数据
  const { isLoading: taskIsLoading } = useTasks(useTasksSearchParams());
  // loading
  const isLoading = taskIsLoading || kanbanIsLoading;

  const onDragEnd = useDragEnd();

  return (
    <Profiler id={'看板页面'}>
      <DragDropContext onDragEnd={onDragEnd}>
        <ScreenContainer>
          <h1>{currentProject?.name}看板</h1>
          <SearchPanel />
          {isLoading ? (
            <Spin size={'large'} />
          ) : (
            <ColumnsContainer>
              <Drop type={'COLUMN'} direction={'horizontal'} droppableId={'kanban'}>
                <DropChild style={{ display: 'flex' }}>
                  {kanbans?.map((kanban, index) => (
                    <Drag key={kanban.id} draggableId={'kanban' + kanban.id} index={index}>
                      <KanbanColumn kanban={kanban} key={kanban.id} />
                    </Drag>
                  ))}
                </DropChild>
              </Drop>
              <CreateKanban />
            </ColumnsContainer>
          )}
          <TaskModal />
        </ScreenContainer>
      </DragDropContext>
    </Profiler>
  );
};

export const useDragEnd = () => {
  // 获取看板的所有数据
  const { data: kanbans } = useKanbans(useKanbanSearchParams());
  // 重新排序看板
  const { mutate: reorderKanban } = useReorderKanban(useKanbansQueryKey());
  // 重新排序 任务
  const { mutate: reorderTask } = useReorderTask(useTasksQueryKey());
  // 获取所有任务
  const { data: allTasks = [] } = useTasks(useTasksSearchParams());

  // 防止重新渲染
  return useCallback(
    ({ source, destination, type }: DropResult) => {
      if (!destination) {
        return;
      }
      // 看板排序
      if (type === 'COLUMN') {
        const fromId = kanbans?.[source.index].id;
        const toId = kanbans?.[destination.index].id;
        if (!fromId || !toId || fromId === toId) {
          return;
        }
        const type = destination.index > source.index ? 'after' : 'before';
        reorderKanban({ fromId, referenceId: toId, type });
      }
      //非同一个看板的排序
      if (type === 'ROW') {
        const fromKanbanId = +source.droppableId;
        const toKanbanId = +destination.droppableId;
        const fromTask = allTasks.filter((task) => task.kanbanId === fromKanbanId)[source.index];
        const toTask = allTasks.filter((task) => task.kanbanId === toKanbanId)[destination.index];
        if (fromTask?.id === toTask?.id) {
          return;
        }
        reorderTask({
          fromId: fromTask?.id,
          referenceId: toTask?.id,
          fromKanbanId,
          toKanbanId,
          type: fromKanbanId === toKanbanId && destination.index > source.index ? 'after' : 'before',
        });
      }
    },
    [kanbans, reorderKanban, allTasks, reorderTask]
  );
};

export const ColumnsContainer = styled('div')`
  display: flex;
  overflow-x: scroll;
  flex: 1;
`;
